#include "Expr2CodeVisitor.h"
#include "AddExpr.h"
#include "SubExpr.h"
#include "MulExpr.h"
#include "DivExpr.h"
#include "ConstExpr.h"

Expr2CodeVisitor::Expr2CodeVisitor(std::ostream& os):m_store(0),m_os(os)
{
    //ctor
}
void Expr2CodeVisitor::Visit(AddExpr* expr){
    expr->Getlhs()->Accept(this);
    this->m_os<<"STO T"<<this->m_store+1<<std::endl;
    this->m_store++;
    expr->Getrhs()->Accept(this);
    this->m_store--;
    this->m_os<<"STO T"<<this->m_store+2<<std::endl;
    this->m_os<<"LOAD T"<<this->m_store+1<<std::endl;
    this->m_os<<"ADD T"<<this->m_store+2<<std::endl;
}
void Expr2CodeVisitor::Visit(SubExpr* expr){
    expr->Getlhs()->Accept(this);
    this->m_os<<"STO T"<<this->m_store+1<<std::endl;
    this->m_store++;
    expr->Getrhs()->Accept(this);
    this->m_store--;
    this->m_os<<"STO T"<<this->m_store+2<<std::endl;
    this->m_os<<"LOAD T"<<this->m_store+1<<std::endl;
    this->m_os<<"SUB T"<<this->m_store+2<<std::endl;
}
void Expr2CodeVisitor::Visit(MulExpr* expr){
    expr->Getlhs()->Accept(this);
    this->m_os<<"STO T"<<this->m_store+1<<std::endl;
    this->m_store++;
    expr->Getrhs()->Accept(this);
    this->m_store--;
    this->m_os<<"STO T"<<this->m_store+2<<std::endl;
    this->m_os<<"LOAD T"<<this->m_store+1<<std::endl;
    this->m_os<<"MUL T"<<this->m_store+2<<std::endl;
}
void Expr2CodeVisitor::Visit(DivExpr* expr){
    expr->Getlhs()->Accept(this);
    this->m_os<<"STO T"<<this->m_store+1<<std::endl;
    this->m_store++;
    expr->Getrhs()->Accept(this);
    this->m_store--;
    this->m_os<<"STO T"<<this->m_store+2<<std::endl;
    this->m_os<<"LOAD T"<<this->m_store+1<<std::endl;
    this->m_os<<"DIV T"<<this->m_store+2<<std::endl;
}
void Expr2CodeVisitor::Visit(ConstExpr* expr){
    this->m_os<<"LOAD "<<expr->Getvalue()<<std::endl;
}
